import { _decorator, Component, Node, sys } from 'cc';
const { ccclass, property } = _decorator;

const URL = 'http://localhost:3000';

@ccclass('HTTP')
export class HTTP extends Component {
    private static instance: HTTP;

    public static getInstance() {
        if (!this.instance) {
            this.instance = new HTTP();
        }
        return this.instance;
    }

    url: string = URL; // 当前URL

    // 发送请求
    sendRequest(path: string, method: string, data: any, callback: Function, url: string = this.url) : XMLHttpRequest {
        const xhr = new XMLHttpRequest();
        xhr.timeout = 50000; // 设置超时时间
        let str = '';
        for (const key in data) {
            if (data.hasOwnProperty(key)) { // 判断对象中是否存在该属性
                str += `${key}=${data[key]}&`; // 拼接参数
            }
        }
        const requestURL = `${url}${path}?${str}`; // 拼接请求URL
        console.log(requestURL);
        xhr.open(method, requestURL, true);
        if (sys.isNative) { // 如果是原生平台
            xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); // 设置请求头
        }

        xhr.onreadystatechange = function () {
            if (xhr.readyState === 4 && (xhr.status >= 200 && xhr.status < 300)) {
                try {
                    const response = JSON.parse(xhr.responseText);
                    if (callback) { // 如果有回调函数，则执行回调函数
                        callback(response);
                    }
                } catch (e) {
                    console.log(e);
                }
            }
        }
        xhr.send(); // 发送请求
        return xhr;
    }
}


